<?php

namespace app\common\model;

use think\Model;
use think\facade\Db;
use app\common\service\Ele;
use app\common\service\Meituan;

/**
 * 美团，饿了么订单获取
 */
class TakeoutOrder extends Model
{
    protected $name = 'takeout_order';

    /**
     * 美团到店订单
     *
     * @param   $startTime  开始支付时间
     * @param   $endTime    结束支付时间
     * @param   $page       页数
     * @param   $size       每页结果数
     */
    public function fetchMeituanPubOrder($params)
    {
        try {
            $model = new \app\common\service\MeituanPub($params['agent_id']);
        } catch (\Exception $e) {
            echo PHP_EOL . $e->getMessage() . PHP_EOL;
            return compact('done', 'update_count');
        }

        $done = 0;
        $update_count = 0;
        $orderList = $model->cpsOrderList($params);
        echo '美团到店' . json_encode($orderList, JSON_UNESCAPED_UNICODE) . PHP_EOL;
        if (empty($orderList['msg']['records'])) {
            return compact('done', 'update_count');
        }
        $orderList = $orderList['msg']['records'];

        foreach ($orderList as $order) {
            $check_order = Db::name($this->name)
                ->field('id, status')
                ->where([
                    'order_id' => $order['uniqueItemId'],
                    'order_type' => TAKEOUT_ORDER_MEITUAN_PUB,
                ])->find();
            $utmMedium = $model->decrypt($order['utmMedium']);
            $user = explode('s', $utmMedium);

            $status = null;
            // 订单状态(1已付款  8已完成  9已退款或风控 10待结算 11已结算)
            switch ($order['itemBizStatus']) {
                case 1: // 支付成功,表示订单已经完成支付
                    $status = 1;
                    break;
                case 2: // 核销成功，表示订单已经到店核验
                    $status = 1;
                    break;
                case 3: // 结算成功，标识订单已经完成结算，会有佣金
                    $status = 8;
                    break;
                case 99: // 无效订单：标识订单无需结算，会有结算失败理
                    $status = 9;
                    break;
                case 999:// 未知状态：异常订单，正常情况下不会出现该状态
                    $status = 9;
                    break;
            }
            if (empty($status)) {
                continue;
            }

            if (empty($check_order)) {
                Db::name($this->name)->insert([
                    'user_id' => $user[0] ?? 0,
                    'agent_id' => $user[1] ?? 0,
                    'channel_id' => $user[2] ?? 0,
                    'order_type' => TAKEOUT_ORDER_MEITUAN_PUB,
                    'order_id' => $order['uniqueItemId'],
                    'paytime' => strtotime($order['orderPayTime']),
                    'ordertime' => strtotime($order['orderPayTime']),
                    'payprice' => yuan2fen($order['actualItemAmount']),
                    'profit' => yuan2fen($order['balanceAmount']),
                    'sid' => $utmMedium,
                    'title' => $order['shopName'],
                    'status' => $status,
                    'img' => $order['shopImage'] ?? '//jj.dmjvip.com/static/images/mt.png',
                    'extra' => json_encode($order, JSON_UNESCAPED_UNICODE),
                    'sub_order_type' => 21,
                ]);
                $done++;
            } else {
                if ($check_order['status'] == 1 && $check_order['status'] != $status) {
                    Db::name($this->name)
                        ->where('id', $check_order['id'])
                        ->update([
                            'status' => $status,
                            'payprice' => yuan2fen($order['actualItemAmount']),
                            'profit' => yuan2fen($order['balanceAmount']),
                            'title' => $order['shopName'],
                            'img' => $order['shopImage'] ?? '//jj.dmjvip.com/static/images/mt.png',
                            'extra' => json_encode($order, JSON_UNESCAPED_UNICODE),
                        ]);
                    $update_count++;
                }
            }
        }

        return compact('done', 'update_count');
    }

    /**
     * 获取饿了么订单
     *
     * @params
     * $startTime   开始时间
     * $endTime     结束时间
     * $alimamaId   cps_alimama 表的 id
     */
    public function fetchEleOrder($params)
    {
        try {
            $ele = new Ele($params['agent_id']);
        } catch (\Exception $e) {
            echo PHP_EOL . $e->getMessage() . PHP_EOL;
            return true;
        }

        $done = 0;
        $update_count = 0;
        $params['limit'] = 100;
        $hasNext = true;
        $page = 1;
        while ($hasNext && $page < 21) {
            $params['page'] = $page;
            $page++;
            $order = $ele->scOrderList($params);
            // {"data":{"has_next":"false","has_pre":"false","page_no":"1","page_size":"100","position_index":"1625576400_|1625587201_"},"request_id":"3q49egyuuvj9"}
            if (empty($order['data']['results']['publisher_order_dto'])) {
                echo 'page = ' . $page . ' --- ' . json_encode($order, JSON_UNESCAPED_UNICODE) . PHP_EOL;
                break;
            }

            echo json_encode($order, JSON_UNESCAPED_UNICODE);


            $orderList = $order['data']['results']['publisher_order_dto'];

            if (empty($order['data']['has_next']) || $order['data']['has_next'] == 'false') {
                $hasNext = false;
            }
            unset($order);
            if (!isset($orderList[0])) {
                $orderList = [$orderList];
            }
            foreach ($orderList as $k2 => $v2) {
                $check_order = Db::name($this->name)
                    ->where('order_id', $v2['trade_parent_id'])
                    ->where('order_type', TAKEOUT_ORDER_ELE)
                    ->find();
                // 淘客订单状态，12-付款，13-关闭，14-确认收货，3-结算成功;不传，表示所有状态
                // 	订单状态( 1 已付款 8 已完成 9 已退款或风控)
                if ($v2['tk_status'] == 12 || $v2['tk_status'] == 14) {
                    $status = 1;
                } elseif ($v2['tk_status'] == 3) {
                    $status = 8;
                } else {
                    $status = 9;
                }

                $adzone_id = $v2['adzone_id'];
                $site_id = $v2['site_id'];

                $sub_pid = $site_id . '_' . $adzone_id;


                $alimamaPid = \app\model\AlimamaPid::where('sub_pid', $sub_pid)->findOrEmpty();

                $true_agent_id = !empty($alimamaPid) ? $alimamaPid->agent_id : 0;


                if (!$true_agent_id) continue;

                if (empty($check_order)) {
                    $click_time = strtotime($v2['click_time']);
                    $info = Db::name('alimama_pid_history')
                        ->where('agent_id', $true_agent_id)
                        ->where('sub_pid', $v2['site_id'] . '_' . $v2['adzone_id'])
                        ->where('start_time', '<=', $click_time)
                        ->where('end_time', '>', $click_time)
                        ->find();
                    Db::name($this->name)
                        ->insert([
                            'agent_id' => $true_agent_id,
                            'order_type' => TAKEOUT_ORDER_ELE,
                            'order_id' => $v2['trade_parent_id'],
                            'paytime' => isset($v2['tk_paid_time']) ? strtotime($v2['tk_paid_time']) : 0,
                            'ordertime' => strtotime($v2['tk_create_time']),
                            'payprice' => yuan2fen($v2['alipay_total_price'] ?? 0),
                            'profit' => yuan2fen($v2['pub_share_pre_fee']),
                            'user_id' => $info['user_id'] ?? 0,
                            'title' => mb_substr($v2['item_title'], 0, 100),
                            'img' => $v2['item_img'],
                            'status' => $status,
                            'extra' => json_encode($v2, JSON_UNESCAPED_UNICODE),
                        ]);
                    $done++;
                } else {
                    if ($check_order['status'] == 1 && $check_order['status'] != $status) {
                        Db::name($this->name)
                            ->where('id', $check_order['id'])
                            ->update([
                                'status' => $status,
                                'extra' => json_encode($v2, JSON_UNESCAPED_UNICODE),
                            ]);
                        $update_count++;
                    }
                }
            }
            unset($orderList);
            sleep(4);
        }

        return compact('done', 'update_count');
    }
}
